package ofpof.domain.dao;

import java.util.Date;

import ofpof.database.MongoDatabaseConnectionProvider;
import ofpof.domain.RemembermeToken;
import ofpof.domain.User;
import ofpof.domain.dao.mapper.RemembermeTokenMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

@Repository
public class RemembermeTokenDao {
	
	@Autowired
	private MongoDatabaseConnectionProvider connectionProvider;

	@Autowired
	private RemembermeTokenMapper remembermeTokenMapper;

	public void create(RemembermeToken remembermeToken) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection remembermeCollection = connection.getCollection("remembermetoken");
		DBObject dbObject = remembermeTokenMapper.toDbObject(remembermeToken);
		remembermeCollection.insert(dbObject);
	}

	public RemembermeToken findByToken(RemembermeToken token) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection remembermeCollection = connection.getCollection("remembermetoken");
		BasicDBObject query = new BasicDBObject();
		query.put("_id",  token.getId());
		query.put("email", token.getEmail());
		query.put("token", token.getToken());
		DBObject dbObject =  remembermeCollection.findOne(query);
		if (dbObject != null) {
			return remembermeTokenMapper.fromDbObject(dbObject);
		}
		return null;
	}

	public void update(RemembermeToken token) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection remembermeCollection = connection.getCollection("remembermetoken");
		BasicDBObject query = new BasicDBObject("_id",token.getId());
		remembermeCollection.update(query, remembermeTokenMapper.toDbObject(token));
	}

	public void deleteTokensOfUser(User user) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection remembermeCollection = connection.getCollection("remembermetoken");
		DBObject query = new BasicDBObject("email",user.getEmail());
		remembermeCollection.remove(query);
	}

	public void deleteOlderThan(Date boundaryDate) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection remembermeCollection = connection.getCollection("remembermetoken");
		DBObject query = new BasicDBObject();
		query.put("createdon", new BasicDBObject("$lte",boundaryDate));
		remembermeCollection.remove(query);
	}

}
